package com.example.walled_houses.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.walled_houses.dto.UserDTO;
import com.example.walled_houses.entity.Opinion;
import com.example.walled_houses.mapper.OpinionMapper;
import com.example.walled_houses.service.OpinionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.walled_houses.utils.UserHolder;
import com.example.walled_houses.vo.Result;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chengtaoxie
 * @since 2023-10-26
 */
@Service
public class OpinionServiceImpl extends ServiceImpl<OpinionMapper, Opinion> implements OpinionService {

    private static final Integer PAGE_SIZE = 5;
    @Resource
    private OpinionMapper opinionMapper;

    /**
     * 增加意见信息
     * @param opinion
     * @return
     */
    @Override
    public Result addOpinion(Opinion opinion) {
        try {
            opinionMapper.insert(opinion);
            return Result.ok().message("添加成功");
        } catch (Exception e) {
            return Result.fail().message("添加失败！");
        }

    }

    /**
     * 删除意见信息
     * @param opinionId
     * @return
     */
    @Override
    public Result deleteOpinion(Integer opinionId) {
        Opinion opinion = opinionMapper.selectById(opinionId);
        if(opinion == null){
            return Result.fail().message("意见不存在！");
        }
        opinionMapper.deleteById(opinionId);
        return Result.ok().message("删除成功");
    }

    /**
     * 分页查询意见信息
     * @param currentPage
     * @return
     */
    @Override
    public Result getOpinion(Integer currentPage) {
        UserDTO userDTO = UserHolder.getUser();
        String userId = userDTO.getUserId();
        QueryWrapper<Opinion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        IPage<Opinion> page = new Page<>(currentPage, PAGE_SIZE);
        IPage<Opinion> opinionPage = opinionMapper.selectPage(page, queryWrapper);
        if(opinionPage == null){
            return Result.fail().message("未查询到数据！");
        }
        return Result.ok(opinionPage);
    }

    /**
     * 修改意见信息
     * @param opinion
     * @return
     */
    @Override
    public Result updateOpinion(Opinion opinion){
        Integer opinionId = opinion.getOpinionId();
        Opinion opinion1 = opinionMapper.selectById(opinionId);
        if(opinion1 == null){
            return Result.fail().message("修改失败");
        }
        opinionMapper.updateById(opinion);
        return Result.ok();
    }
}
